package top.kaoshanji.p1ch02c;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import java.lang.invoke.MethodHandles;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;

/**
 * 代码清单 p1ch02c-17：MethodHandles.Lookup#unreflect的使用示例(反射API与方法句柄的交互)
 * author kaoshanji
 * ^_^
 * create time 2025/1/3 15:37
 */
public class MethodHandlesLookupExample04 {

    private static final Logger logger = LogManager.getLogger(MethodHandlesLookupExample04.class);

    public static void main(String[] args) throws NoSuchMethodException, IllegalAccessException, NoSuchFieldException {
        logger.info("...代码清单 p1ch02c-17：MethodHandles.Lookup#unreflect的使用示例(反射API与方法句柄的交互)...");

        MethodHandles.Lookup lookup = MethodHandles.lookup();

        // String#构造器
        Constructor constructor = String.class.getConstructor(byte[].class);
        lookup.unreflectConstructor(constructor);

        // String#substring
        Method method = String.class.getMethod("substring", int.class, int.class);
        lookup.unreflect(method);

        // 本类的私有方法 privateMethod
        Method privateMethod = MethodHandlesLookupExample04.class.getDeclaredMethod("privateMethod");
        lookup.unreflectSpecial(privateMethod, MethodHandlesLookupExample04.class);

        // 本类的字段 name
        Field field = MethodHandlesLookupExample04.class.getField("name");
        lookup.unreflectGetter(field);
        lookup.unreflectSetter(field);

    }

    private void privateMethod() {}

    public String name;

}
